<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@page import="java.io.File"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.PrintWriter"%>
<%@page import="java.util.List"%>
<%@page import="java.util.UUID"%>
<%@page import="javax.servlet.annotation.WebServlet"%>
<%@page import="javax.servlet.http.HttpServlet"%>
<%@page import="javax.servlet.http.HttpServletRequest"%>
<%@page import="javax.servlet.http.HttpServletResponse"%>
<%@page import="javax.servlet.http.HttpSession"%>

<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="com.pojo.User"%>
<%@page import="com.Dao.UserDaox"%>
<%@page import="com.google.gson.Gson"%>
<%
try {
	// 1. ������������
	FileItemFactory factory = new DiskFileItemFactory();
	// 2. �ļ��ϴ����Ĺ�����
	ServletFileUpload upload = new ServletFileUpload(factory);
	// ���ô�С���Ʋ���
	upload.setFileSizeMax(10*1024*1024);// �����ļ���С���ƣ��˴�Ϊ10M
	upload.setSizeMax(500*1024*1024);	// ���ļ���С���ƣ��˴�Ϊ500M
	upload.setHeaderEncoding("UTF-8");	// �������ļ����봦��
	// 3. ����������ת��Ϊlist����
	List<FileItem> list = upload.parseRequest(request);
	// ����
	for(FileItem item : list){
		// �жϣ���ͨ�ı�����
		if (item.isFormField()){
			// ��ȡ����
			String name = item.getFieldName();
			// ��ȡֵ
			String value = item.getString();
			//ת��ΪUTF-8����
			value = new String(value.getBytes("ISO8859-1"),"UTF-8");
			System.out.println(name+"��"+value);
		} 
		// �ļ�����
		else {
			/******** �ļ��ϴ� ***********/
			// a. ��ȡ�ļ�����
			String name = item.getName();
			String fileName = null;
            int ind = name.lastIndexOf("\\");
            if (ind != -1) {
                fileName = name.substring(ind + 1);
            }else {
                fileName = name;
            }
			// a1. �ȵõ�Ψһ���(���ɵ�Ψһ�ַ���������������������Ѿ����ڵ��ļ�ͬ��)
			String id = UUID.randomUUID().toString();
			// a2. ƴ���ļ���
			name = id + fileName;	
			// b. �õ��ϴ�Ŀ¼
			String basePath=getServletContext().getRealPath("/file");
			String basePathx="F:\\apache-tomcat-9.0.5-windows-x86\\apache-tomcat-9.0.5\\wtpwebapps\\file";
			// c. ����Ҫ�ϴ����ļ�����
			File file = new File(basePath,name);
			File filex = new File(basePathx,name);
			// d. �ϴ�
			System.out.println(filex);
			item.write(file);
			Integer uid =((User)session.getAttribute("user")).getUid();
			UserDaox userDao =new UserDaox(); 
			userDao.findpasd(uid, name);
			Gson gson = new Gson();
			String jsonStr = gson.toJson(name);
			PrintWriter outx = response.getWriter();
			outx.print(jsonStr);
		}
		
		
	}
} catch (Exception e) {
	e.printStackTrace();
}
%>
